<template>
  <Row>
    <i-col>
      <slot :data="rows" :sortChange="sortChange">

      </slot>
      <slot name="footer" >

      </slot>
      <Page :total="pagination.total" :current.sync="pagination.current" :page-size="pagination.pageSize"
            v-if="pagination.total>0"
            style="margin-top: 20px"
            show-total
            show-elevator
            :show-sizer="showSizer"
            :page-size-opts="pageSizeOpts"
            @on-change="pageOnChange"
            @on-page-size-change="pageSizeChange"></Page>
    </i-col>
  </Row>
</template>
<script>
  import _ from 'lodash'
  // 0为异步请求方式，1为静态分页模式
  let requestMode = {
    async: 0,
    static: 1
  }
  export default {
    name: 'tablePage',
    data () {
      let rows = []
      let pagination = {
        current: 1,
        total: 0,
        pageSize: this.pageSizeOpts[0]
      }
      let orderByObj = {} // 内部排序对象，主要实现iview排序，单排序 复杂排序通过 customParam 排序
      let customParam = {} // 刷新用到的自定义函数,每次查询后参数制空
      let datas = {rows, pagination, customParam, orderByObj}
      return datas
    },
    props: {
      filterMethod: {
        type: Function,
        default (obj) {
          return obj
        }
      },
      /* 是否启动加载 */
      isStartLoad: {
        type: Boolean,
        default: true
      },
      mode: {
        type: Number,
        default: requestMode.async
      },
      /* 静态数据 */
      staticData: {
        type: Array,
        default () {
          return []
        }
      },
      url: {
        type: String,
        default: null
      },
      api: {
        type: Function,
        default () {
          return Promise.reject(new Error('tablePage api接口错误'))
        }
      },
      /* 初始化查询参数 */
      param: {
        type: Object,
        default () {
          return {}
        }
      },
      /* 初始化查询 排序字段 */
      sortName: {
        type: String,
        default () {
          return ''
        }
      },
      /* 初始化查询 排序类型 */
      sortType: {
        type: String,
        default () {
          return ''
        }
      },
      /* 是否显示分页条数 */
      showSizer: {
        type: Boolean,
        default: false
      },
      /* 分页条数 */
      pageSizeOpts: {
        type: Array,
        default () {
          return [10, 20, 30, 40]
        }
      }
    },
    methods: {
      /**
       * TODO(获得当前所有行的原始数据)
       * @auther zhangQ
       * @date 2018/3/22 17:48
       */
      getRows () {
        return this.rows
      },
      /**
       * TODO(刷新当前页面)
       * @auther zhangQ
       * @date 2018/3/26 12:02
       */
      dataRefreshCurrentPage (paramClone) {
        if (paramClone && typeof paramClone === 'object') {
          this.customParam = paramClone
        }
        this.readLoad()
      },
      /**
       * TODO(刷新)
       * @auther zhangQ
       * @date 2018/2/18 17:28
       **/
      dataRefresh (paramClone) {
        this.pagination.current = 1
        if (paramClone && typeof paramClone === 'object') {
          this.customParam = paramClone
        }
        this.readLoad()
      },
      /**
       * 获取数据
       * @param pagination 分页数据
       */
      readLoad () {
        if (this.mode === requestMode.async) {
          this.getDatas()
        } else if (this.mode === requestMode.static) {
          this.staticLoadPage()
        }
      },
      /**
       * 静态数据分页
       * @param pagination 分页数据
       */
      staticLoadPage () {
        if (this.staticData && this.staticData.length > 0) {
          this.rows = []
          setTimeout(() => {
            let param = this.getAjaxParam()
            let staticDataClone = _.cloneDeep(this.staticData)
            if (param.sortName && param.sortName !== '') {
              staticDataClone = _.sortBy(staticDataClone, function (o) {
                return o[param.sortName]
              })
              if (param.sortOrder === 'desc') {
                staticDataClone.reverse()
              }
            }
            let start = (param.pageNumber - 1) * param.pageSize
            let end = param.pageNumber * param.pageSize
            this.rows = staticDataClone.slice(start, end)
            this.pagination.total = staticDataClone.length
          }, 200)
        } else {
          this.rows = []
          if (this.pagination.current > 1) {
            this.pagination.current = 1
          }
        }
      },
      /**
       * 获取数据
       */
      getDatas () {
        this.api(this.getAjaxParam()).then((response) => {
          let resData = response.data
          if (!resData.data) {
            return Promise.reject(new Error('没有数据'))
          }
          this.pagination.total = resData.data.total
          if (this.filterMethod && typeof this.filterMethod === 'function') {
            this.rows = this.filterMethod(resData.data.rows)
          } else {
            this.rows = resData.data.rows
          }
        }).catch((error) => {
          console.log(error)
        })
      },
      /**
       * 获取 ajax 参数
       * @returns {{pageNumber: *, pageSize: number, obj: (props.param|{type, default}|HTMLParamElement|*), sortName: *, sortOrder: string}}
       */
      getAjaxParam () {
        let type = 'desc'
        if (this.sortType !== 'desc' && this.sortType !== 'asc') {
          if (this.sortType === 'ascending') {
            type = 'asc'
          }
        } else {
          type = this.sortType
        }
        let resObj = Object.assign({
          pageNumber: this.pagination.current,
          pageSize: this.pagination.pageSize,
          sortName: this.sortName,
          sortOrder: type
        }, this.param, this.orderByObj, this.customParam)
        // 每次获取参数完毕把customParam 制空
        this.customParam = {}
        return resObj
      },
      pageSizeChange (pageSize) {
        this.pagination.pageSize = pageSize
        this.readLoad()
      },
      pageOnChange (pageNumber) {
        this.pagination.current = pageNumber
        this.readLoad()
        this.$emit('pageChangeIndex', pageNumber, this.pagination.pageSize)
      },
      /**
       * 排序改变
       */
      sortChange ({key, order}) {
        if (key) {
          let sortObj = {
            sortName: key,
            sortOrder: order
          }
          if (order === 'normal') {
            sortObj = {}
          }
          this.orderByObj = sortObj
          this.dataRefresh()
        } else {
          console.error('列名不存在')
        }
      }
    },
    mounted () {
      this.$watch(() => {
        return this.sortName + this.sortType
      }, (newVal, oldVal) => {
        this.readLoad()
      })
      if (this.mode === requestMode.static) {
        this.$watch('staticData.length', function (newVal, oldVal) {
          this.dataRefresh()
        })
      }
      this.isStartLoad && this.readLoad()
    }
  }
</script>
<style scoped>
</style>
